package team.hyznrj.studentsys.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ReMidDream
 * @date 2018-02-27 16:27
 **/
public class CookieUtil {

    public static void set(HttpServletResponse response,
                           String name,String value,
                           int maxAge){
        Cookie cookie = new Cookie(name,value);
        cookie.setPath("/");
        cookie.setMaxAge(7200);
        response.addCookie(cookie);
    }

    public static Cookie get(HttpServletRequest request,
                             String name){
        Map<String, Cookie> cookieMap = readCookie(request);
        return cookieMap != null ? cookieMap.getOrDefault(name, null) : null;
    }

    private static Map<String,Cookie> readCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies==null) {
            return null;
        }
        Map<String,Cookie> map = new HashMap<>();
        for (Cookie cookie : cookies) {
            map.put(cookie.getName(),cookie);
        }
        return map;
    }
}
